<template>
  <div class="w-full h-full relative">
    <video
      ref="video"
      :style="{ height: props.height }"
      class="w-full h-full"
      autoplay
      muted
      controls
      loop
    />
    <el-button
      v-if="isPlayback"
      class="absolute bottom-10 right-1/2"
      @click="handleQuitPlayback"
      >退出回放</el-button
    >
  </div>
</template>

<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { SrsRtcPlayerAsync } from "../utils/srsRtc.js";

interface CameraData {
  type?: string;
  data?: string;
}

const props = defineProps<{
  height?: string;
  data: CameraData;
}>();

const emit = defineEmits(["quitPlayback"]);

const video = ref();
let srs;

watch(
  () => props.data,
  () => {
    checkCameraDataType();
  }
);

onMounted(() => {
  checkCameraDataType();
});

function checkCameraDataType() {
  video.value.srcObject = null;
  if (srs) {
    srs.close();
  }
  if (!props.data.data) {
    return;
  }
  if (props.data.type === "stream") {
    srs = new SrsRtcPlayerAsync();
    video.value.srcObject = srs.stream;
    srs.play(props.data.data);
  }
  if (props.data.type === "playback") {
    video.value.src = props.data.data;
  }
}

const isPlayback = computed(() => {
  return status.value === "playback";
});

const status = computed(() => {
  return props.data.type;
});

function handleQuitPlayback() {
  video.value.src = null;
  emit("quitPlayback");
}

onBeforeUnmount(() => {
  if (srs) {
    srs.close();
  }
});
</script>
